package cn.inbot.shopadmin.module.mine.view;

import android.annotation.SuppressLint;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.os.Bundle;
import android.provider.Settings;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.TextPaint;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.LinkMovementMethod;
import android.text.method.PasswordTransformationMethod;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.ActivityOptionsCompat;

import com.alibaba.android.arouter.facade.annotation.Route;

import org.jetbrains.annotations.Nullable;

import java.util.Locale;

import cn.inbot.shopadmin.R;
import cn.inbot.shopadmin.app.AppCacheData;
import cn.inbot.shopadmin.app.RouterUrls;
import cn.inbot.shopadmin.module.mine.viewmodel.LoginViewModel;
import cn.inbot.lib.framework.PBApplication;
import cn.inbot.lib.framework.annotation.InjectLayout;
import cn.inbot.lib.framework.mvvm.java.PBJVMActivity;
import cn.inbot.lib.framework.router.PBRouter;
import cn.inbot.lib.widget.LoadingDialogHelper;

import static cn.inbot.lib.util.ext.ToastExtKt.showToast;

/**
 * Created by shisenkun on 2021/5/11.
 */
@Route(path = RouterUrls.DEMO_LOGIN)
@InjectLayout(layoutResId = R.layout.activity_login)
public class LoginActivity extends PBJVMActivity<LoginViewModel> {

    private EditText etUsername;
    private EditText etPassword;
    private Button btnLogin;
    // 是否显示密码，需要设置密码可见属性和图片的切换
    private ImageView btnPassword;
    private boolean isShow = false;
    // 接受协议的按钮，需要进行图片的切换
    private ImageView acceptBox;
    // 判断用户是否同意了协议
    private boolean isAccept = false;
    private TextView acceptText;
    // 登录方式，需要设置隐藏或者更换textView的具体内容
    private TextView loginWay;
    private boolean isLoginByIdentify = false;
    // 密码框和验证码框
    private ConstraintLayout layoutPassword;
    private ConstraintLayout layoutIdentify;
    // 获取验证码的按钮
    private Button getCode;
    private TextView identifyText;

    Locale curLocale;
    SpannableString hintText;
    AbsoluteSizeSpan hintSize;

    /**
     * 初始化视图
     *
     * @param savedInstanceState
     */
    @SuppressLint("WrongConstant")
    @Override
    public void initView(@Nullable Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        // 获取控件
        etUsername = findViewById(R.id.etUsername);
        etPassword = findViewById(R.id.etPassword);
        etPassword.setInputType(129);
        btnLogin = findViewById(R.id.btnLogin);
        btnPassword = findViewById(R.id.display_password);
        acceptBox = findViewById(R.id.accept_box);
        acceptText = findViewById(R.id.accept_text);
        loginWay = findViewById(R.id.login_way);
        layoutPassword = findViewById(R.id.constraintLayout_password);
        layoutIdentify = findViewById(R.id.constraintLayout_identify);
        getCode = findViewById(R.id.get_code);
        identifyText = findViewById(R.id.identify_text);

        // 将用户名和密码进行记录
        etUsername.setText(AppCacheData.getLastLoginUsername());
        etPassword.setText(AppCacheData.getLastLoginPassword());

        // 获得当前系统语言
        curLocale = getResources().getConfiguration().locale;

        // 为显示密码的按钮设置点击事件
        btnPassword.setOnClickListener(v -> {
            if (isShow) {
                // 设置密码可见
                etPassword.setInputType(128);
                btnPassword.setImageResource(R.mipmap.show_password);
                isShow = !isShow;
            } else {
                // 设置密码不可见
                etPassword.setInputType(129);
                btnPassword.setImageResource(R.mipmap.hide_password);
                isShow = !isShow;
            }
            //设置光标位置
            etPassword.setSelection(etPassword.getText().toString().length());
        });

        // 为是否勾选用户协议设置点击事件，更换图片
        acceptBox.setOnClickListener(v -> {
            if (isAccept == false) {
                isAccept = true;
                acceptBox.setImageResource(R.mipmap.accept_box);
            } else {
                isAccept = false;
                acceptBox.setImageResource(R.mipmap.accept_box1);
            }

        });

        // 为登录按钮设置点击事件
        btnLogin.setOnClickListener(v -> {
//            String username = etUsername.getText().toString();
//            String password = etPassword.getText().toString();
//            String androidId = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
//            LoadingDialogHelper.INSTANCE.build(getSupportFragmentManager()).show();
//            viewModel.login(username, password, androidId);
            forwardMainActivity();

        });

        // 修改hint提示字体的大小
        hintText = new SpannableString(getString(R.string.hint_text_verification_code));
        hintSize = new AbsoluteSizeSpan(14, true);
        hintText.setSpan(hintSize, 0, hintText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        identifyText.setHint(hintText);

        // 为选择的登录方式设置点击事件,设置密码框和验证码框的显示和隐藏
        loginWay.setOnClickListener(v -> {
            // 去到验证码登录阶段
            if (!isLoginByIdentify || layoutPassword.getVisibility() == 0) {
                layoutPassword.setVisibility(View.INVISIBLE);
                layoutIdentify.setVisibility(View.VISIBLE);
                isLoginByIdentify = true;

                //通过Locale的equals方法，判断出当前语言环境
                if (curLocale.equals(Locale.SIMPLIFIED_CHINESE)) {
                    //中文
                    loginWay.setText("密码登录");
                } else {
                    //英文
                    loginWay.setText("Password login");
                }
            // 去到密码登录阶段
            } else {
                layoutPassword.setVisibility(View.VISIBLE);
                layoutIdentify.setVisibility(View.INVISIBLE);
                isLoginByIdentify = false;

                //通过Locale的equals方法，判断出当前语言环境
                if (curLocale.equals(Locale.SIMPLIFIED_CHINESE)) {
                    //中文
                    loginWay.setText("使用验证码登录");
                } else {
                    //英文
                    loginWay.setText("Login with verification code");
                }

            }

        });

        // 为获取验证码的按钮设置点击事件
        getCode.setOnClickListener(v -> {
            showToast("获取验证码");
        });


        // 设置用户进行协议的点击
        SpannableStringBuilder spannableString = new SpannableStringBuilder();
        spannableString.append("我已阅读并同意《派宝智能货柜机用户协议》、《隐私政策》，并授权派宝使用该账号信息。");

        //货柜协议的点击事件
        ClickableSpan clickableSpan = new ClickableSpan() {
            @Override
            public void onClick(View view) {
                showToast("派宝智能货柜机用户协议");
            }

            /**
             * 重写updateDrawState,去除下划线
             * @param ds
             */
            @Override
            public void updateDrawState(TextPaint ds) {
                ds.setUnderlineText(false);
                ds.setColor(Color.parseColor("#009ad6"));
            }

        };
        spannableString.setSpan(clickableSpan, 7, 20, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        //隐私政策的点击事件
        ClickableSpan clickableSpan1 = new ClickableSpan() {
            @Override
            public void onClick(View view) {
                showToast("隐私政策");
            }

            /**
             * 重写updateDrawState,去除下划线
             * @param ds
             */
            @Override
            public void updateDrawState(TextPaint ds) {
                ds.setUnderlineText(false);
                ds.setColor(Color.parseColor("#009ad6"));
            }

        };
        spannableString.setSpan(clickableSpan1, 21, 27, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        acceptText.setText(spannableString);
        acceptText.setMovementMethod(LinkMovementMethod.getInstance());

    }

    @Override
    protected void onResume() {
        super.onResume();
        // 无使用toolbar
//        setupToolbar(R.id.toolbar, true, true).setTitle("登陆");
//        getSupportActionBar().setHomeAsUpIndicator(R.mipmap.ic_close);
//        immersiveStatusBar(R.color.colorPrimary, true);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_login, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_item_regist: {
                PBRouter.INSTANCE
                        .buildWithDefaultAnim(RouterUrls.DEMO_REGIST)
                        .withOptionsCompat(ActivityOptionsCompat.makeCustomAnimation(
                                this, R.anim.slide_bottom_in, R.anim.slide_bottom_none))
                        .navigation();
                PBApplication.mainHandler.postDelayed(() -> finish(), 300);
            }
            break;
        }
        return true;
    }

    @Override
    public void startObserve() {
        super.startObserve();
        viewModel.loginResponseWrapper.observe(this, loginResultResponseWrapper -> {
            //LoadingDialogHelper.hide()
            if (loginResultResponseWrapper.getData() != null) {
                showToast("登陆成功");
                finish();
            } else {
                showToast("登陆失败,错误码:${it.exception!!.errorCode}");
            }
        });

    }

    /**
     * 完成
     */
    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(
                R.anim.slide_bottom_none,
                R.anim.slide_bottom_out
        );
    }

    /**
     * 跳转到主活动
     */
    private void forwardMainActivity() {
        PBRouter.INSTANCE.buildWithDefaultAnim(RouterUrls.DEMO_MAIN).navigation();
        finish();
    }


}
